<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统设置 - 个人设置</title>
    <link rel="stylesheet" href="../../css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script type="module" src="../../js/components/navigation.js"></script>
    <script type="module" src="../../js/utils.js"></script>
    <script type="module" src="../../js/api.js"></script>
</head>
<body>
    <div class="loading-overlay" id="loading-overlay">
        <div class="loading-spinner"></div>
    </div>

    <div class="toast" id="toast"></div>

    <div class="app-container">
        <header class="app-header">
            <div class="logo">
                <i class="fas fa-building"></i> 员工管理系统
            </div>
            <div class="user-info">
                <span id="username-display" class="username"></span>
                <button id="logout-btn" class="btn btn-secondary">
                    <i class="fas fa-sign-out-alt"></i> 退出登录
                </button>
            </div>
        </header>

        <div class="app-body">
            <aside class="sidebar" id="main-menu">
                <nav class="menu">
                    <ul>
                        <li><a href="#" class="menu-item active" data-target="welcome">
                            <i class="fas fa-home"></i> 欢迎页
                        </a></li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">
                                <i class="fas fa-users"></i> 员工管理
                            </a>
                            <ul class="submenu">
                                <li><a href="../employee/list.html" class="submenu-item">
                                    <i class="fas fa-list"></i> 员工列表
                                </a></li>
                                <li><a href="../employee/add.html" class="submenu-item">
                                    <i class="fas fa-plus"></i> 添加员工
                                </a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">
                                <i class="fas fa-briefcase"></i> 业务管理
                            </a>
                            <ul class="submenu">
                                <li><a href="../business/list.html" class="submenu-item">
                                    <i class="fas fa-list"></i> 业务列表
                                </a></li>
                                <li><a href="../business/create.html" class="submenu-item">
                                    <i class="fas fa-plus"></i> 创建业务
                                </a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">
                                <i class="fas fa-money-bill-wave"></i> 薪酬管理
                            </a>
                            <ul class="submenu">
                                <li><a href="../salary/overview.html" class="submenu-item">
                                    <i class="fas fa-chart-line"></i> 薪酬概览
                                </a></li>
                                <li><a href="../salary/manage.html" class="submenu-item">
                                    <i class="fas fa-cog"></i> 薪酬管理
                                </a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">
                                <i class="fas fa-cog"></i> 系统设置
                            </a>
                            <ul class="submenu">
                                <li><a href="../system/user.html" class="submenu-item">
                                    <i class="fas fa-user-cog"></i> 用户管理
                                </a></li>
                                <li><a href="../system/profile.html" class="submenu-item active">
                                    <i class="fas fa-user"></i> 个人设置
                                </a></li>
                            </ul>
                        </li>
                    </ul>
                </nav>
            </aside>

            <main class="content">
                <div class="page-header">
                    <h1><i class="fas fa-user-circle"></i> 个人设置</h1>
                    <div class="breadcrumb">
                        <a href="#"><i class="fas fa-home"></i> 首页</a> &gt;
                        <a href="#"><i class="fas fa-cog"></i> 系统设置</a> &gt;
                        <span><i class="fas fa-user"></i> 个人设置</span>
                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-header">
                        <h2><i class="fas fa-user"></i> 个人信息</h2>
                    </div>
                    <div class="card-body">
                        <div class="profile-info">
                            <div class="profile-avatar-container">
                                <div class="profile-avatar" id="profile-avatar">
                                    <img src="https://picsum.photos/150" alt="个人头像" id="avatar-image">
                                </div>
                                <div class="avatar-upload">
                                    <button id="change-avatar-btn" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-upload"></i> 更换头像
                                    </button>
                                    <input type="file" id="avatar-file" accept="image/*" style="display: none;">
                                </div>
                            </div>

                            <div class="profile-details">
                                <form id="basic-info-form">
                                    <input type="hidden" id="user-id" name="id">
                                    <div class="row">
                                        <div class="form-group col-md-6">
                                            <label for="username" class="form-label">用户名</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text"><i class="fas fa-user"></i></span>
                                                </div>
                                                <input type="text" id="username" name="username" class="form-control" disabled>
                                            </div>
                                        </div>

                                        <div class="form-group col-md-6">
                                            <label for="real-name" class="form-label">真实姓名 <span class="text-danger">*</span></label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text"><i class="fas fa-id-card"></i></span>
                                                </div>
                                                <input type="text" id="real-name" name="realName" class="form-control" placeholder="请输入真实姓名">
                                            </div>
                                            <div class="invalid-feedback" id="real-name-error"></div>
                                        </div>

                                        <div class="form-group col-md-6">
                                            <label for="email" class="form-label">邮箱 <span class="text-danger">*</span></label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text"><i class="fas fa-envelope"></i></span>
                                                </div>
                                                <input type="email" id="email" name="email" class="form-control" placeholder="请输入邮箱">
                                            </div>
                                            <div class="invalid-feedback" id="email-error"></div>
                                        </div>

                                        <div class="form-group col-md-6">
                                            <label for="phone" class="form-label">手机号 <span class="text-danger">*</span></label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text"><i class="fas fa-phone"></i></span>
                                                </div>
                                                <input type="tel" id="phone" name="phone" class="form-control" placeholder="请输入手机号">
                                            </div>
                                            <div class="invalid-feedback" id="phone-error"></div>
                                        </div>

                                        <div class="form-group col-md-6">
                                            <label for="gender" class="form-label">性别</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text"><i class="fas fa-venus-mars"></i></span>
                                                </div>
                                                <select id="gender" name="gender" class="form-control">
                                                    <option value="">请选择性别</option>
                                                    <option value="male">男</option>
                                                    <option value="female">女</option>
                                                    <option value="other">其他</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="form-group col-md-6">
                                            <label for="birth-date" class="form-label">出生日期</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text"><i class="fas fa-calendar-day"></i></span>
                                                </div>
                                                <input type="date" id="birth-date" name="birthDate" class="form-control">
                                            </div>
                                        </div>

                                        <div class="form-group col-md-12">
                                            <label for="address" class="form-label">地址</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text"><i class="fas fa-map-marker-alt"></i></span>
                                                </div>
                                                <textarea id="address" name="address" rows="3" class="form-control" placeholder="请输入地址"></textarea>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="action-buttons mt-3 text-right">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-save"></i> 保存
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h2><i class="fas fa-lock"></i> 修改密码</h2>
                    </div>
                    <div class="card-body">
                        <form id="change-password-form">
                            <div class="row">
                                <div class="form-group col-md-12">
                                    <label for="current-password" class="form-label">当前密码 <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text"><i class="fas fa-key"></i></span>
                                        </div>
                                        <input type="password" id="current-password" name="currentPassword" class="form-control" placeholder="请输入当前密码">
                                    </div>
                                    <div class="invalid-feedback" id="current-password-error"></div>
                                </div>

                                <div class="form-group col-md-12">
                                    <label for="new-password" class="form-label">新密码 <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                        </div>
                                        <input type="password" id="new-password" name="newPassword" class="form-control" placeholder="请输入新密码">
                                    </div>
                                    <div class="invalid-feedback" id="new-password-error"></div>
                                    <div class="password-strength mt-2" id="password-strength">
                                        <div class="strength-meter"></div>
                                        <div class="strength-text"></div>
                                    </div>
                                </div>

                                <div class="form-group col-md-12">
                                    <label for="confirm-password" class="form-label">确认新密码 <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                        </div>
                                        <input type="password" id="confirm-password" name="confirmPassword" class="form-control" placeholder="请确认新密码">
                                    </div>
                                    <div class="invalid-feedback" id="confirm-password-error"></div>
                                </div>
                            </div>

                            <div class="action-buttons mt-3 text-right">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-exchange-alt"></i> 修改密码
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script>
        import { api } from '../../js/api.js';
        <!-- 移除ES6模块导入，使用全局对象 -->
        import { initNavigation } from '../../js/components/navigation.js';

        document.addEventListener('DOMContentLoaded', function() {
            // 初始化导航
            initNavigation('main-menu', '系统设置', '个人设置');

            // 检查登录状态
            checkLoginStatus();

            // 显示用户名
            const username = localStorage.getItem('username');
            if (username) {
                document.getElementById('username-display').textContent = username;
            }

            // 退出登录
            document.getElementById('logout-btn').addEventListener('click', function() {
                localStorage.removeItem('token');
                localStorage.removeItem('username');
                window.location.href = '../../index.html';
            });

            // 头像上传相关
            const changeAvatarBtn = document.getElementById('change-avatar-btn');
            const avatarFile = document.getElementById('avatar-file');
            const avatarImage = document.getElementById('avatar-image');

            changeAvatarBtn.addEventListener('click', function() {
                avatarFile.click();
            });

            avatarFile.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    // 显示加载状态
                    showLoading(true);

                    // 模拟上传头像
                    setTimeout(() => {
                        const reader = new FileReader();
                        reader.onload = function(event) {
                            avatarImage.src = event.target.result;
                            showToast('头像上传成功', 'success');
                            showLoading(false);
                        };
                        reader.readAsDataURL(file);
                    }, 1000);
                }
            });

            // 加载用户信息
            loadUserInfo();

            // 基本信息表单提交事件
            const basicInfoForm = document.getElementById('basic-info-form');
            basicInfoForm.addEventListener('submit', function(e) {
                e.preventDefault();

                // 表单验证
                if (!validateBasicInfoForm()) {
                    return;
                }

                // 显示加载状态
                showLoading(true);

                // 获取表单数据
                const formData = {
                    id: document.getElementById('user-id').value.trim(),
                    realName: document.getElementById('real-name').value.trim(),
                    email: document.getElementById('email').value.trim(),
                    phone: document.getElementById('phone').value.trim(),
                    gender: document.getElementById('gender').value.trim(),
                    birthDate: document.getElementById('birth-date').value.trim(),
                    address: document.getElementById('address').value.trim()
                };

                // 提交表单数据
                api.user.updateProfile(formData)
                    .then(response => {
                        showLoading(false);
                        if (response) {
                            showToast('保存成功', 'success');
                        } else {
                            showToast('保存失败', 'error');
                        }
                    })
                    .catch(error => {
                        showLoading(false);
                        console.error('Failed to update profile:', error);
                        showToast('保存失败，请重试', 'error');
                    });
            });

            // 密码强度检测
            const newPasswordInput = document.getElementById('new-password');
            const passwordStrength = document.getElementById('password-strength');
            const strengthMeter = passwordStrength.querySelector('.strength-meter');
            const strengthText = passwordStrength.querySelector('.strength-text');

            newPasswordInput.addEventListener('input', function() {
                const password = this.value;
                if (password.length === 0) {
                    passwordStrength.style.display = 'none';
                    return;
                }

                passwordStrength.style.display = 'block';
                const strength = checkPasswordStrength(password);

                // 更新强度指示器
                strengthMeter.className = 'strength-meter';
                strengthText.className = 'strength-text';

                switch(strength) {
                    case 'weak':
                        strengthMeter.classList.add('weak');
                        strengthText.classList.add('weak');
                        strengthText.textContent = '弱';
                        break;
                    case 'medium':
                        strengthMeter.classList.add('medium');
                        strengthText.classList.add('medium');
                        strengthText.textContent = '中';
                        break;
                    case 'strong':
                        strengthMeter.classList.add('strong');
                        strengthText.classList.add('strong');
                        strengthText.textContent = '强';
                        break;
                    case 'very-strong':
                        strengthMeter.classList.add('very-strong');
                        strengthText.classList.add('very-strong');
                        strengthText.textContent = '非常强';
                        break;
                }
            });

            // 修改密码表单提交事件
            const changePasswordForm = document.getElementById('change-password-form');
            changePasswordForm.addEventListener('submit', function(e) {
                e.preventDefault();

                // 表单验证
                if (!validatePasswordForm()) {
                    return;
                }

                // 显示加载状态
                showLoading(true);

                // 获取表单数据
                const formData = {
                    id: document.getElementById('user-id').value.trim(),
                    currentPassword: document.getElementById('current-password').value.trim(),
                    newPassword: document.getElementById('new-password').value.trim()
                };

                // 提交表单数据
                api.user.changePassword(formData)
                    .then(response => {
                        showLoading(false);
                        if (response) {
                            showToast('密码修改成功', 'success');
                            // 清空表单
                            changePasswordForm.reset();
                            passwordStrength.style.display = 'none';
                        } else {
                            showToast('密码修改失败，当前密码不正确', 'error');
                        }
                    })
                    .catch(error => {
                        showLoading(false);
                        console.error('Failed to change password:', error);
                        showToast('密码修改失败，请重试', 'error');
                    });
            });

            function checkLoginStatus() {
                const token = localStorage.getItem('token');
                if (!token) {
                    window.location.href = '../../index.html';
                }
            }

            function loadUserInfo() {
                // 显示加载状态
                showLoading(true);

                // 假设当前登录用户ID存储在localStorage中
                const userId = localStorage.getItem('userId') || '1';

                api.user.getDetail(userId)
                    .then(user => {
                        showLoading(false);
                        if (user) {
                            // 填充表单数据
                            document.getElementById('user-id').value = user.id;
                            document.getElementById('username').value = user.username;
                            document.getElementById('real-name').value = user.realName || '';
                            document.getElementById('email').value = user.email || '';
                            document.getElementById('phone').value = user.phone || '';
                            document.getElementById('gender').value = user.gender || '';
                            document.getElementById('birth-date').value = user.birthDate || '';
                            document.getElementById('address').value = user.address || '';

                            // 更新头像（如果有）
                            if (user.avatar) {
                                document.getElementById('avatar-image').src = user.avatar;
                            }
                        } else {
                            showToast('未找到用户信息', 'error');
                        }
                    })
                    .catch(error => {
                        showLoading(false);
                        console.error('Failed to load user info:', error);
                        showToast('加载用户信息失败，请重试', 'error');
                    });
            }

            function validateBasicInfoForm() {
                let isValid = true;

                // 重置错误提示
                resetErrors();

                // 验证真实姓名
                const realName = document.getElementById('real-name').value.trim();
                if (!realName) {
                    showError('real-name', '请输入真实姓名');
                    isValid = false;
                }

                // 验证邮箱
                const email = document.getElementById('email').value.trim();
                if (!email) {
                    showError('email', '请输入邮箱');
                    isValid = false;
                } else if (!Validator.isEmail(email)) {
                    showError('email', '请输入有效的邮箱');
                    isValid = false;
                }

                // 验证手机号
                const phone = document.getElementById('phone').value.trim();
                if (!phone) {
                    showError('phone', '请输入手机号');
                    isValid = false;
                } else if (!Validator.isPhoneNumber(phone)) {
                    showError('phone', '请输入有效的手机号');
                    isValid = false;
                }

                return isValid;
            }

            function validatePasswordForm() {
                let isValid = true;

                // 重置错误提示
                resetPasswordErrors();

                // 验证当前密码
                const currentPassword = document.getElementById('current-password').value.trim();
                if (!currentPassword) {
                    showError('current-password', '请输入当前密码');
                    isValid = false;
                }

                // 验证新密码
                const newPassword = document.getElementById('new-password').value.trim();
                if (!newPassword) {
                    showError('new-password', '请输入新密码');
                    isValid = false;
                } else if (newPassword.length < 6) {
                    showError('new-password', '新密码长度不能少于6位');
                    isValid = false;
                } else if (checkPasswordStrength(newPassword) === 'weak') {
                    showError('new-password', '密码强度不足，请使用更复杂的密码');
                    isValid = false;
                }

                // 验证确认新密码
                const confirmPassword = document.getElementById('confirm-password').value.trim();
                if (!confirmPassword) {
                    showError('confirm-password', '请确认新密码');
                    isValid = false;
                } else if (newPassword !== confirmPassword) {
                    showError('confirm-password', '两次输入的新密码不一致');
                    isValid = false;
                }

                // 验证新密码与当前密码是否相同
                if (currentPassword === newPassword) {
                    showError('new-password', '新密码不能与当前密码相同');
                    isValid = false;
                }

                return isValid;
            }

            function checkPasswordStrength(password) {
                let score = 0;

                // 长度检查
                if (password.length >= 8) score++;
                if (password.length >= 12) score++;

                // 复杂度检查
                if (/[A-Z]/.test(password)) score++;
                if (/[a-z]/.test(password)) score++;
                if (/[0-9]/.test(password)) score++;
                if (/[^A-Za-z0-9]/.test(password)) score++;

                // 判断强度
                if (score <= 2) return 'weak';
                if (score <= 4) return 'medium';
                if (score <= 5) return 'strong';
                return 'very-strong';
            }

            function showError(fieldId, message) {
                const field = document.getElementById(fieldId);
                const errorElement = document.getElementById(fieldId + '-error');

                field.classList.add('is-invalid');
                errorElement.textContent = message;
                errorElement.style.display = 'block';
            }

            function resetErrors() {
                // 重置基本信息表单错误
                const fields = ['real-name', 'email', 'phone'];
                fields.forEach(fieldId => {
                    const field = document.getElementById(fieldId);
                    const errorElement = document.getElementById(fieldId + '-error');

                    field.classList.remove('is-invalid');
                    errorElement.textContent = '';
                    errorElement.style.display = 'none';
                });
            }

            function resetPasswordErrors() {
                // 重置密码表单错误
                const fields = ['current-password', 'new-password', 'confirm-password'];
                fields.forEach(fieldId => {
                    const field = document.getElementById(fieldId);
                    const errorElement = document.getElementById(fieldId + '-error');

                    field.classList.remove('is-invalid');
                    errorElement.textContent = '';
                    errorElement.style.display = 'none';
                });
            }

            function showToast(message, type) {
                const toast = document.getElementById('toast');
                toast.textContent = message;
                toast.className = 'toast show ' + type;

                setTimeout(() => {
                    toast.className = 'toast';
                }, 3000);
            }

            function showLoading(show) {
                const loadingOverlay = document.getElementById('loading-overlay');
                loadingOverlay.style.display = show ? 'flex' : 'none';
            }
        });
    </script>
</body>
</html>